package priv.wangy.micro.common.po.echarts;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <a href="https://echarts.apache.org/examples/zh/editor.html?c=line-simple">...</a>
 *
 * @author zhangjq
 * @since 2024-11-15
 */
@Data
public class LineSimpleChart {

    @JsonProperty("xAxis")
    private XAxis xAxis;

    @JsonProperty("yAxis")
    private YAxis yAxis;

    private List<Series> series;

    @Data
    public static class XAxis {

        private String type;

        private List<String> data;
    }

    @Data
    public static class YAxis {

        private String type;
    }

    @Data
    public static class Series {

        private String type;

        private boolean smooth;

        private List<Integer> data;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {

        private final List<String> xAxisData = new ArrayList<>();

        private final List<Map<String, Integer>> lineList = new ArrayList<>();

        public Builder addLine(Map<String, Integer> data) {
            data.keySet().forEach(key -> {
                if (!xAxisData.contains(key)) {
                    xAxisData.add(key);
                }
            });
            this.lineList.add(data);
            return this;
        }

        public LineSimpleChart build() {
            LineSimpleChart chart = new LineSimpleChart();
            XAxis xAxis = new XAxis();
            xAxis.setType("category");
            Collections.sort(this.xAxisData);
            xAxis.setData(new ArrayList<>(this.xAxisData));
            YAxis yAxis = new YAxis();
            yAxis.setType("value");
            List<Series> seriesList = this.lineList.stream().map(line -> {
                Series series = new Series();
                series.setType("line");
                series.setSmooth(true);
                series.setData(this.xAxisData.stream().map(x -> line.getOrDefault(x, 0)).toList());
                return series;
            }).toList();
            chart.setXAxis(xAxis);
            chart.setYAxis(yAxis);
            chart.setSeries(seriesList);
            return chart;
        }
    }
}
